<template>
  <div class="login-container">
    <div class="login-form">
      <h2 class="login-title">医疗系统登录</h2>
      
      <van-form @submit="onSubmit">
        <van-cell-group inset>
          <van-field
            v-model="formData.userName"
            name="userName"
            label="用户名"
            placeholder="请输入用户名"
            :rules="[{ required: true, message: '请输入用户名' }]"
          />
          
          <van-field
            v-model="formData.password"
            type="password"
            name="password"
            label="密码"
            placeholder="请输入密码"
            :rules="[{ required: true, message: '请输入密码' }]"
          />
        </van-cell-group>
        
        <div style="margin: 16px;">
          <van-button round block type="primary" native-type="submit" :loading="loading">
            登录
          </van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { showToast } from 'vant';
import { useUserStore } from '@/stores/user';

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();

const formData = ref({
  userName: '',
  password: ''
});

const loading = ref(false);

const onSubmit = async (values) => {
  loading.value = true;
  
  try {
    await userStore.login(values);
    
    showToast({
      type: 'success',
      message: '登录成功',
      onClose: () => {
        // 如果有重定向的页面，则跳转到该页面
        const redirectPath = route.query.redirect || '/patients';
        router.replace(redirectPath);
      }
    });
  } catch (error) {
    console.error('登录失败', error);
    showToast({
      type: 'fail',
      message: '用户名或密码错误'
    });
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: var(--background-color);
}

.login-form {
  width: 100%;
  max-width: 400px;
  padding: 20px;
}

.login-title {
  text-align: center;
  margin-bottom: 30px;
  color: var(--primary-color);
}
</style> 